/* DirClient.java
 * Jeremiah Theurer
 * This file contains the code for the Directory Server client for VOIP app.
 */

import java.net.*;
import java.io.*;

public class DirClient
{
	Socket socket = null;
	BufferedReader in = null;
	PrintWriter out = null;
	
	public DirClient(String serverName, int port)//Constructor handles all socket creating and what not.
	{
		try
		{
			System.out.println("Creating socket...");
			socket = new Socket(serverName, port);
			System.out.println("Socket created!");
			
			System.out.println("Creating reader...");
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			System.out.println("Reader created!");
			
			System.out.println("Creating writer...");
			out = new PrintWriter(socket.getOutputStream(), true);
			System.out.println("Writer created!");
		}
		catch(IOException e)
		{
			System.err.println(e.getMessage());
			System.exit(1);
		}
	}

	public String[] getUsers(String user)//Method to get users.  Takes no arguments
	{
		String[] users = null;
		out.println("get users");
		out.println(user);
		try
		{
			String size = in.readLine();
			int num = Integer.parseInt(size);
			users = new String[num-1];
			for(int i = 0; i < users.length; i++)
			{
				users[i] = in.readLine();
			}
		}
		catch(IOException e)
		{
			System.err.println("Failed to get users.");
		}
		return users;
	}
	
	public void login(String user, String ip)//Method to "login" a new user.  Basically just adds the Username and IP in the args to the server.
	{
		out.println("login");
		out.println(user);
		out.println(ip);
	}
	
	public void logout(String user, String ip)//Method to "logout" a user.  Basically just removes the Username and IP in the args from the server.
	{
		out.println("logout");
		out.println(user);
		out.println(ip);
	}
	
	public String getIP(String user)//Method to get the IP address for the arg user as a string.
	{
		out.println("get ip");
		out.println(user);
		try
		{
			String ip = in.readLine();
			return ip;
		}
		catch(IOException e)
		{
			System.err.println("Failed to get IP");
			return null;
		}
		
	}
	
	public void closeAll()//Closes all connections to the server that this instance of DirClient has.
	{
		try
		{
			System.out.println("Closing...");
			socket.close();
			in.close();
			System.out.println("Closed!");
		}
		catch(IOException e)
		{
			System.err.println("Could not close everything");
		}
	}
}
